#!/usr/bin/env python3

# wget.py - operations for wget
#
# Copyright (c) 2019-2023 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import re
import pathlib
from ._util import LastUpdateTime
from ._main import AppStat, AppImplBase


class AppImpl(AppImplBase):

    _BINARY_PATH = "/usr/bin/wget"

    _REFERENCE_IMPLEMENTATION_BINARY_PATH = "/usr/bin/wget-reference"

    _ETC_CFG_PATH = "/etc/wgetrc"

    @staticmethod
    def get_name():
        return "wget"

    def is_installed(self):
        return os.path.exists(self._BINARY_PATH)

    def system_get_info(self, app_data_dir):
        if not self.is_installed():
            return (AppStat.NOT_INSTALLED, None, None)

        appStat, msg = self._parseAndCheckWgetrc(self._BINARY_PATH)
        if appStat == AppStat.FULLY_ROBUSTIFIED:
            if not self._isRobustExtensionInstalled():
                appStat = AppStat.PARTIALLY_ROBUSTIFIED
                msg = ", ".join(["wget robust extension is not installed", msg])
            return (appStat, msg, LastUpdateTime.read(app_data_dir))
        elif appStat == AppStat.NOT_ROBUSTIFIED or appStat == AppStat.NOT_MANAGEABLE:
            return (appStat, msg, None)
        else:
            assert False

    def system_robustify_config(self, app_data_dir):
        self._modifyWgetrc(self._ETC_CFG_PATH)
        LastUpdateTime.write(app_data_dir)

    def user_get_info(self):
        assert False

    def user_robustify_config(self, username):
        assert False

    def _isRobustExtensionInstalled(self):
        if not os.path.exists(self._REFERENCE_IMPLEMENTATION_BINARY_PATH):
            return False

        try:
            if os.path.basename(self._REFERENCE_IMPLEMENTATION_BINARY_PATH) not in pathlib.Path(self._BINARY_PATH).read_text():
                return False
        except ValueError:
            # failed to decode to text
            return False

        return True

    def _parseAndCheckWgetrc(self, filepath):
        if not os.path.exists(filepath):
            return (AppStat.NOT_ROBUSTIFIED, "")
        if not os.path.isfile(filepath):
            return (AppStat.NOT_MANAGEABLE, "%s is not a file" % (self._ETC_CFG_PATH))

        buf = pathlib.Path(self._ETC_CFG_PATH).read_text()
        bPartial = False
        msg = ""

        # infinite retrying
        m = re.search(r"^\s*tries\s*=\s*0\s*$", buf, re.M)
        if m is None:
            return (AppStat.NOT_ROBUSTIFIED, "")

        # wait time between retries of failed
        m = re.search(r"^(\s*|#\s*)waitretry\s*=\s*(\S+)\s*$", buf, re.M)
        if m is not None and not m.group(1).startswith("#"):
            try:
                if int(m.group(2)) < 10:
                    bPartial = True
                    msg = "waitretry is too small"
            except ValueError:
                return (AppStat.NOT_MANAGEABLE, "invalid value for waitretry")
        else:
            # default value of waitretry is good
            pass

        if not bPartial:
            return (AppStat.FULLY_ROBUSTIFIED, msg)
        else:
            return (AppStat.PARTIALLY_ROBUSTIFIED, msg)

    def _modifyWgetrc(self, filepath):
        if os.path.exists(filepath):
            buf = pathlib.Path(self._ETC_CFG_PATH).read_text()
        else:
            buf = ""

        # infinite retrying
        buf, count = re.subn(r"^.*tries\s*=.*$", "tries = 0", buf, flags=re.M)
        if count == 0:
            buf = buf.rstrip("\n")
            buf += "\n"
            buf += "tries = 0\n"

        # wait time between retries of failed
        m = re.search(r"^\s*waitretry\s*=\s*(\S+)\s*$", buf, re.M)
        if m is not None:
            try:
                if int(m.group(1)) < 10:
                    buf = buf.replace(m.group(0), "waitretry = 10")
            except ValueError:
                # we don't modify if value is invalid
                pass
        else:
            # default value of waitretry is good
            pass

        with open(filepath, "w") as f:
            f.write(buf)


class CmdLineContext:

    @property
    def param(self):
        return [
            "--tries=0",                                    # infinite retrying
            "--random-wait",                                # random interval between multiple retrieval
            "--dns-timeout=10", "--connect-timeout=10",     # we don't modify "--read-timeout" here so that the connection is kept as long as possible
        ]
